'use strict';
app.controller('flowCtrl', ['$scope', '$modal', '$rootScope', '$http', '$filter', '$stateParams', '$timeout', 'lodash','$location', function ($scope, $modal, $rootScope, $http, $filter, $stateParams, $timeout, lodash,$location) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    var saveBtn = {
        show: true,
        label: '保存',
        func: function () {
            // updateFlowDetails();
            updateFlowDetails2();
        }
    };
    var backUrl = {
        show: true,
        label: "返回",
        func: function () {
            $rootScope.backHistory();
        }
    };
    var backFlow = {
        show: true,
        label: "返回场景",
        func: function () {
            $scope.info.selectedFlow.type = 1;
            $scope.info.jumpToFeature = "";
            // $scope.info.currentDiagram = true;
            // $scope.showFlowBuilder = true;
        }
    }; 
    var jumpUrl = {
        show: true,
        label: "流程架构",
        func: function () {
            window.open('#/app/repository/flow/');
        }
    };

    $scope.settings.btnEle.push(saveBtn);
    $scope.settings.btnEle.push(backUrl); 
    $scope.settings.btnEle.push(backFlow); 
    if($rootScope.isMatrixCusRole('matrix_sys_admin')){
       $scope.settings.btnEle.push(jumpUrl);
    }
    //结束headerElement设置

    $scope.reqDetails = {};
    $scope.info = {
        addNum         : 0,   //记录点击添加的次数，用户给新创建的图例定位
        currentReqId   : $stateParams.reqId ? $stateParams.reqId : "-1",
        statusList     : config_flow_node_status,
        flowTypeArray  : [{"crtname": "功能点", "type": "feature"}, {"crtname": "流程", "type": "flow"}],
        diagramStatus  : "current",
        sltStatusItem  : "",
        nameAndVersion : "",
        relateFeatures : [],    //req关联的feature数据
        flowData       : [],    //流程结构数据集合
        flowTree       : [],    //流程数据集合
        my_tree        : {},
        isFeature      : true,
        isDisabled     : true,
        viewStatus     : "current",
        flowArray      : [],
        selectedFlow   : {},     //当前选中的节点对象
        input          : "",     //输入内容（查询画板中的流程节点）
        selectValue    : "1",    //已有节点下拉框的选中值
        flowId         : "",     //更新时所需的flowId
        flowDetails    : {},     //点击的流程详细数据
        legendList     : [],     //点击flow时获取图例列表
        featureList    : [],     //全部功能点
        reqFlows       : [],     //req关联的流程列表
        reqRelateFlows : [],     //req关联的列表（状态为ADD，UPDATE）
        reqNodeFlows   : [],     //req关联的流程（状态为NODE_UPDATE）
        featureDisabled: true,   //默认不可点击
        diagram        : null,
        jumpToFeature  : null,   //跳转到的featureId
        hasRelate      : false,  //是否被关联   true：是   false：否
        removeFinished : false,  //删除后，树上的按钮是否显示 true: 显示  false: 否
        currentDiagram : true,   //req不为-1时，显示当前diagram
        masterDiagram  : false,  //req为-1时，显示master的diagram
        nodeDataArray  : [],
        linkDataArray  : [],
        selectedNodeData  : [],
        customLegendArray: [
            {feature_lengend_id: "c01", category: "Start", text: "开始"},
            {feature_lengend_id: "c02", category: "Next", text: "下一步"},
            {feature_lengend_id: "c03", category: "Diamond", text: "判断", figure: "Diamond"},
            {feature_lengend_id: "c04", category: "End", text: "结束"},
            {feature_lengend_id: "c05", category: "Comment", text: "描述"},
            {feature_lengend_id: "c06", category: "Line", text: "线","length":50},
            {feature_lengend_id: "c08", category: "vLine", text: "竖线","length":50},
            {feature_lengend_id: "c07", category: "User", text: "用户"},
        ],
        customFeatureArray: [],
        sltLegendItem: "",   //选择的图例数据
        reqFlowDatas: {},
        masterFlowDatas: {},
        diagramScope: {},
        diagramSelected: "",
        reqFlowList: [],
        reqFeatureList: [],
        originNodeDataArray: [],
        originLinkDataArray: [],
    };
    
    //定义节点数据和节点线数据
    $scope.info.model = new go.GraphLinksModel([], []);
    $scope.info.modelMaster = new go.GraphLinksModel([], []);
    $scope.info.model.selectedFlowData = null;
    $scope.info.modelMaster.selectedFlowData = null;
    $scope.info.mDiagram = null;   //设置画布只读时需要
    $scope.info.mDiagramMaster = null;   //设置画布只读时需要
    //定义节点工具框内容
    $scope.info.paModel = new go.GraphLinksModel($scope.info.customLegendArray);
    $scope.info.paModelMaster = new go.GraphLinksModel($scope.info.customLegendArray);

    getReqFlows($scope.info.currentReqId);
    getFlowTree();
    setDesignTabName();

    getFlowTreeData();

    //获取流程树数据
    function getFlowTreeData() {
        var url = matrix_product_url + "/flow/getFlowTree";
        $rootScope.showPanelLoading();
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                if (!result.data) {
                    $rootScope.toasterErrorInfo("获取流程树数据错误！");
                } else {
                    $scope.info.flowData = setFlowTree([result.data], []);
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $scope.info.nodeDetails = "";
            $rootScope.hidePanelLoading();
        });
    };

    //解析流程树
    function setFlowTree(flowData, flowArray) {
        angular.forEach(flowData, function (flowItem, index) {
            flowItem.key = flowItem.id;
            flowItem.parent = flowItem.parentId;
            flowItem.isRelate = lodash.findWhere($scope.info.reqFlows, {id: flowItem.id});
            flowArray.push(flowItem);
            if (flowItem.children && flowItem.children.length) {
                setFlowTree(flowItem.children, flowArray);
            }
        });
        return flowArray;
    }

    setFlowHeight();

    function setFlowHeight() {
        $timeout(function() {        
            var h = document.documentElement.clientHeight || document.body.clientHeight;
            if($scope.info.reqNodeFlows.length) {
                h = (h - 155)/2;
                var d = h - 100;
            } else {
                h = h - 155;
                var d = h - 100;
            }
            $("#flow-builder-content").css("height", h + "px");
            $(".row-flow").css("height", h + "px");
            $(".req-relate-flow").css({
                "max-height": d +"px",
                "overflow": "auto",
            });
        }, 500)
    }

    $(window).resize(function() {
        setFlowHeight();
    });

    //获取产品设计名称
    function setDesignTabName() {
        var url = matrix_product_url +"/brdRequirement/getBrdRequirements?reqId="+ $stateParams.reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    $scope.reqDetails = result.data[0];
                    $scope.breadcrumb.push('产品设计',$scope.reqDetails.reqName);
                }
            }
        });
    }

    //获取流程树
    function getFlowTree() {
        var url = matrix_product_url + "/flow/getFlowTree";
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.info.flowTree = result.data.children;
                $scope.info.flowArray = setFlowLegendPath(result.data.children, [], "");
                setDiagramReadonly(true);
                getReqRelateFeature();
                $timeout(function() {
                    var firstBranch = lodash.first($scope.info.flowTree);
                    $scope.info.my_tree.set_select_branch_by_id(firstBranch.id);
                }, 500);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //解析流程树数据
    function setFlowLegendPath(featureTree, resultFeatureArray, featureName) {
        angular.forEach(featureTree, function (feature, index) {
            var pathUrl = featureName ? featureName + "/" + feature.name : feature.name;
            //type  1: frame   2: flow
            if(feature.type == "2") {
                var featureItem = {
                    crtname: pathUrl,
                    category: "formula",
                    text: pathUrl ? "P: "+ lodash.last(pathUrl.split("/")) : "",
                    nodeType: "flow",
                    //feature_id: feature.id,
                    //isHighlighted: feature.status ? (feature.status == "ADD" ? true : false) : false,
                    isHighlighted: "flow",
                    feature_info: {
                        id: feature.id,
                        sys: "",
                        type: feature.type,
                        title: pathUrl ? pathUrl : "",
                        status: feature.status ? feature.status : "ADD",
                        relate_id: "",
                        relate_type: "",
                        relate_name: lodash.last(pathUrl.split("/")),
                        relate_path: pathUrl,
                        bussiness_line_id: feature.metaData.bussinessId,
                    },
                    status: feature.status ? feature.status : "ADD",
                    sys: "",
                    relate_name: lodash.last(pathUrl.split("/")),
                    relate_path: pathUrl,
                }
                resultFeatureArray.push(featureItem);
            }
            if (feature.children && feature.children.length) {
                setFlowLegendPath(feature.children, resultFeatureArray, feature.name);
            }
        });
        return resultFeatureArray;
    };

    //点击树获取节点信息
    $scope.my_tree_handler = function (branch) {
        console.log("----查看流程节点数据----");
        console.log(branch);
        $scope.info.selectedFlow = branch;
        $scope.info.sltLegendItem = "";
        $scope.info.legendList = [];
        $scope.info.removeFinished = false;
        if (branch.type == "2") {   //判断是否为flow节点（1： frame节点 2：flow节点）
            $scope.info.isDisabled = false;
            $scope.info.addNum = 0;
            //getFlowDetailsOfLegend(branch.id, "2");
            getFeatureList();
            var isRelateFlow = lodash.findWhere($scope.info.reqFlows, {id: branch.id});
            if(isRelateFlow == undefined) {    //isRelateFlow undefined: 未被关联   
                setDiagramMasterReadonly(true);
                $scope.info.viewStatus = "online";
                $scope.info.diagramStatus = "online";
                $scope.info.isDisabled = true;
                $scope.info.jumpToFeature = "";
                getFlowDetailsOfNode(branch.id, "-1");
            } else {
                setDiagramReadonly(false);
                $scope.info.viewStatus = "current";
                $scope.info.diagramStatus = "current";
                $scope.info.jumpToFeature = branch.id;
                getFlowDetailsOfNode(branch.id, $scope.info.currentReqId);
            }
        } else {
            $scope.info.isDisabled = true;
            $scope.info.jumpToFeature = "";
            setDiagramReadonly(true);
            //getFlowDetailsOfLegend(branch.id, "1");
            //frame节点，初始化画布为空
            $scope.info.model = new go.GraphLinksModel([], []);
        }
    };

    //设置画布是否只读
    function setDiagramReadonly(status) {
        // $scope.info.mDiagram.setProperties({
        //     isReadOnly: status
        // });
    };

    //设置master画布是否只读
    function setDiagramMasterReadonly(status) {
        // $scope.info.mDiagramMaster.setProperties({
        //     isReadOnly: status
        // });
    }

    //获取全部的功能点（用于选择功能点然后添加到流程图模板组件中）
    function getFeatureList() {
        var url = matrix_product_url +"/feature/getFeature?withPrototype=1&withAttr=0";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.featureDisabled = false;
                var featureList = [];
                angular.forEach(result.data, function(res, index) {
                    if(res.path) {                        
                        var itemName = res.type == "PROTOTYPE" ? res.featureName+"【"+ lodash.last(res.path.split("/")) +"】" : res.featureName;
                        var item = {
                            crtname: "..." + res.path.substring(17),
                            category: "formula",
                            text: res.path ? "F: "+ itemName : "F: "+lodash.last(res.path.split("/")),
                            feature_id: res.id,
                            nodeType: "feature",
                            //isHighlighted: res.status ? (res.status == "ADD" ? true : false) : false,
                            isHighlighted: "",
                            feature_info: {
                                id: res.id,
                                sys: res.sys,
                                type: res.type,
                                title: res.featureName ? itemName : "",
                                status: res.status ? res.status : "ADD",
                                relate_id: "",
                                relate_type: "",
                                relate_name: (res.type == "PROTOTYPE" ? lodash.last(res.path.split("/")) : res.featureName),
                                relate_path: res.path,
                                bussiness_line_id: res.bussinessLine,
                            },
                            status: res.status ? res.status : "ADD",
                            sys: res.sys,
                            relate_name: (res.type == "PROTOTYPE" ? lodash.last(res.path.split("/")) : res.featureName),
                            relate_path: res.path,
                        }
                        // resultLegendArray.push(item);
                        featureList.push(item);
                    }
                });
                $scope.info.featureList = featureList;
                //var orderByLegend = $filter('orderBy')(resultLegendArray, "index", false);
                //$scope.info.paModel = new go.GraphLinksModel(orderByLegend);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //获取flow的节点详细信息
    function getFlowDetailsOfNode(flowId, reqId) {
        $scope.showFlowBuilder = false;
        var url = matrix_product_url +"/flow/getFlowDetail?flowId="+ flowId +"&reqId="+ reqId;
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                if (!result.data) {
                    $rootScope.toasterErrorInfo("获取流程信息错误！");
                    return false;
                }

                $scope.info.hasRelate = lodash.findWhere($scope.info.reqFlows, {id: result.data.id});
                $scope.info.flowId = result.data.id;
                $scope.info.flowDetails = result.data;
                // $scope.info.nameAndVersion = {"name": result.data.name, "version": "v"+(result.data.attrs != null ? result.data.attrs.version : "")};
                $scope.info.nameAndVersion = {"name": result.data.name};
                if (!result.data.attrs) {
                    $scope.info.model = new go.GraphLinksModel([], []);
                    return false;
                }
                angular.forEach(result.data.attrs.nodeDataArray, function(node) {
                    // node.flag = setStatusByCn(node.flag);
                    node.featureKind = node.featureKind || "JUMP";
                    node.isOldItem = node.isOldItem == "oldItem" ? "oldItem" : "newItem";
                    node.isNew = node.isNew || "无";  
                    if(node.isRelate == undefined || node.isRelate == null) {
                        node.isRelate = "";
                    }
                    if(node.category == "Feature") {
                        node.feature_id = node.id || "";
                        var reqRelateIndex = lodash.findIndex($scope.info.relateFeatures, function(feature) {
                            return feature.id == node.id;
                        });
                        if(reqRelateIndex != -1) {
                            node.isRelate = "isRelate";
                        }
                    } else {
                        var reqRelateIndex = lodash.findIndex($scope.info.reqFlows, function(flow) {
                            return flow.id == node.id;
                        });
                        if(reqRelateIndex != -1) {
                            node.isRelate = "isRelate";
                        }
                    }
                    if(node.feature_info) {
                        node.nodeStatus = "";
                        node.nodeStatus = (node.feature_info.status == "UPDATE" ? "/功能改动" : "");
                    }
                    if(node.flow_info) {
                        node.nodeStatus = "";
                        node.nodeStatus = (node.flow_info.status == "UPDATE" ? "/流程改动" : "")
                    }
                    node.flag = (node.isNew || "") + (node.nodeStatus || "");
                });

                $scope.info.originNodeDataArray = result.data.attrs.nodeDataArray;
                $scope.info.originLinkDataArray = result.data.attrs.linkDataArray;
                if(reqId == "-1") {
                    $scope.info.masterFlowDatas = {"nodeDataArray": result.data.attrs.nodeDataArray || [{ "key":1, "text":"Start", "category":"Start", "loc": "-500 0" }], "linkDataArray": result.data.attrs.linkDataArray || []};
                } else {
                    $scope.info.reqFlowDatas = {"nodeDataArray": result.data.attrs.nodeDataArray || [{ "key":1, "text":"Start", "category":"Start", "loc": "-500 0"  }], "linkDataArray": result.data.attrs.linkDataArray || []};
                }

                $scope.info.nodeDataArray = result.data.attrs.nodeDataArray;
                $scope.info.linkDataArray = result.data.attrs.linkDataArray;
                switch($scope.info.diagramStatus) {
                    case "current":
                        $scope.info.currentDiagram = true;
                        $scope.info.masterDiagram = false;
                        setDiagramReadonly(false);
                        break;
                    case "online":
                        $scope.info.currentDiagram = false;
                        $scope.info.masterDiagram = true;
                        setDiagramMasterReadonly(true);
                        break;
                    case "compare":
                        $scope.info.currentDiagram = true;
                        $scope.info.masterDiagram = true;
                        reqId == "-1" ? setDiagramMasterReadonly(true) : setDiagramReadonly(true);
                        break;
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $scope.showFlowBuilder = true;
        });
    };

    // 设置中文状态显示
    function setStatusByCn(status) {
        var statusName = "";
        switch(status) {
            case "ONLINE": 
                statusName = "无";
                break;
            case "ADD": 
                statusName = "新增";
                break;
            case "UPDATE": 
                statusName = "修改";
                break;
            default: 
                statusName = "无";
        }
        return statusName;
    }

    //获取当前req关联的功能点数据
    function getReqRelateFeature() {
        var url = matrix_product_url +"/feature/getAllFeatureForReq?reqId="+ $scope.info.currentReqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.relateFeatures = result.data ? result.data : [];
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //更新flow节点的详细信息（更新flow的attrs）
    function updateFlowDetails() {
        var isRelateFlow = lodash.findWhere($scope.info.reqFlows, {id: $scope.info.selectedFlow.id});
        if(isRelateFlow == undefined) {
            return false;
        }
        var nodeArray = $scope.info.model.nodeDataArray;
        var linkArray = $scope.info.model.linkDataArray;
        var nodeDataArray = $scope.info.nodeDataArray;
        var linkDataArray = $scope.info.linkDataArray;
        var currentDate = Number(new Date());
        var postParams = {
            reqId: $stateParams.reqId ? $stateParams.reqId : "-1",
            flowId: $scope.info.flowId, 
            attrs: {
                "date": currentDate,
                "version": $scope.info.flowDetails.attrs.version,
                "req_snapshot": $scope.info.flowDetails.attrs.req_snapshot,
                "master_version": $scope.info.flowDetails.attrs.master_version,
                "nodeDataArray": nodeDataArray ? nodeDataArray : nodeArray,
                "linkDataArray": linkDataArray ? linkDataArray : linkArray,
            }
        };
        console.log(JSON.stringify(preventCircularJson(postParams)));
        var url = matrix_product_url + "/flow/updateReqFlowContent";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                $rootScope.toasterSuccessInfo("保存成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //解决转换json时的bug
    function preventCircularJson(source, censoredMessage, censorTheseItems) {
        censorTheseItems = censorTheseItems || [source];
        censoredMessage = censoredMessage || "CIRCULAR_REFERENCE_REMOVED";
        var recursiveItems = {};
        var ret = {};
        for (var key in source) {
            var value = source[key]
            if (typeof value == "object") {
                recursiveItems[key] = value;
            } else {
                ret[key] = value;
            }
        }
        var censorChildItems = [];
        for (var key in recursiveItems) {
            var value = source[key];
            censorChildItems.push(value);
        }
        for (var key in recursiveItems) {
            var value = source[key];
            var censored = false;
            censorTheseItems.forEach(function (item) {
                if (item === value) {
                    censored = true;
                }
            });
            if (censored) {
                value = censoredMessage;
            } else {
                value = preventCircularJson(value, censoredMessage, censorChildItems.concat(censorTheseItems));
            }
            ret[key] = value
        }
        return ret;
    }

    // 添加流程框架
    $scope.addFrame = function(nodeData) {
        openFlowModal("add", "frame", nodeData);
    };

    //添加流程方法
    $scope.addFlow = function (nodeData) {
        $scope.info.selectedNodeData = nodeData;
        openFlowModal("add", "", "");
    };

    //编辑流程
    $scope.editFlow = function (nodeData) {
        // $scope.info.reqNodeFlows = [];
        // $scope.info.reqRelateFlows = [];
        $scope.info.selectedNodeData = nodeData;
        openFlowModal("edit", nodeData, "");
    };

    //复制流程
    $scope.copyFlow = function (nodeData) {
        $scope.info.selectedNodeData = nodeData;
        openFlowModal("copy", nodeData, $scope.info.flowDetails);
    };

    //打开流程模态框
    function openFlowModal(type, defaultValue, flowDetails) {
        if (!$scope.info.selectedFlow) {
            $rootScope.toasterWarningInfo("请先选择流程！");
            return false;
        }
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/flowNodeModal.html"),
            controller: "editFlowCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                type: function () {
                    return type;
                },
                defaultValue: function () {
                    return defaultValue;
                },
                flowDetails: function () {
                    return flowDetails;
                }
            }
        });

        modalInstance.result.then(function (flowName) {
            if (defaultValue == "frame") {
                editFrameDetails(flowName, type);
            } else {
                editFlowDetails(flowName, type);
            }
        }, function (reason) {
            console.log("关闭modal");
        });
    };

    //编辑流程架构节点信息
    function editFrameDetails(nodeName, type) {
        var postParams = {
            name: nodeName.name,
            type: "FLOW_FRAME",   //1：架构  2：流程
            isDel: "1",
            level: "" + (parseInt($scope.info.diagramSelected.level) + 1),
            children: [],
            parentId: $scope.info.diagramSelected.id
        };
        if (type == "edit") {
            $scope.info.diagramSelected.name = nodeName;
            postParams = $scope.info.diagramSelected;
        }
        if (type == "move") {
            postParams.id = $scope.info.diagramSelected.id;
            postParams.name = $scope.info.diagramSelected.name;
            postParams.level = nodeName.level;
            postParams.parentId = nodeName.id;
            postParams.children = nodeName.children;
        }
        var url = matrix_product_url + "/flowFrame/saveFlowFrame";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                if ('add' == type) {
                    $http.get(matrix_product_url + "/flowFrame/getTreeNode?flowFrameId=" + result.data).success(function (result) {
                        if (result.code == "0") {
                            $scope.addNodeToTree(result.data);
                        }
                    });
                } else if ("edit" == type) {
                    $scope.info.diagramScope.updateNode();
                } else if ("move" == type) {
                    $http.get(matrix_product_url + "/flowFrame/getTreeNode?flowFrameId=" + postParams.id).success(function (result) {
                        if (result.code == "0") {
                            $scope.info.diagramScope.moveNode(setFlowTree([result.data], [])[0]);
                        }
                    });
                }
                $rootScope.toasterSuccessInfo(type == "add" ? "架构添加成功！" : (type == "move" ? "移动成功！" : "修改成功！"));
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    }

    //编辑流程（创建，修改，复制）
    function editFlowDetails(flowData) {
        var url = matrix_product_url +(flowData.type != "edit" ? "/flow/createFlow" : "/flow/updateMasterFlow");

        var flowDetails = $scope.info.selectedNodeData;
        var postParams = {
            name: flowData.name,
            reqId: $stateParams.reqId ? $stateParams.reqId : "-1",
        };
        if (flowData.type == "add") {
            postParams.bussinessId = flowDetails.id;
        }
        if (flowData.type == "edit") {
            postParams.id = flowDetails.id;
        }
        if (flowData.type == "copy") {
            postParams.bussinessId = flowData.id;
            postParams.attrs = flowData.attrs;
        }
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                if (flowData.type != "edit") {
                    var flowItem = {
                        id: result.data.id,
                        name: result.data.name,
                        parentId: result.data.bussinessId,
                        type: "2",
                        level: parseInt($scope.info.selectedFlow.level) + 1,
                        isDel: "1",
                        children: [],
                        metaData: result.data
                    };
                    if (flowData.type == "add") {
                        if (!$scope.info.selectedFlow.children.length) {
                            $scope.info.selectedFlow.children = [];
                        }
                        flowItem.status = "ADD";
                        flowItem.isRelate = "red";
                        $scope.info.selectedFlow.children.push(flowItem);
                        $scope.info.reqFlows.push(result.data);
                        // console.log($scope.info.reqFlows);
                        // if($scope.info.reqFlows.length == 0) {
                        //     if($scope.info.selectedNodeData.status == "NODE_UPDATE") {
                        //         $scope.info.reqNodeFlows.push(flowItem);
                        //     } else {
                        //         $scope.info.reqRelateFlows.push(flowItem);
                        //     }
                        // } else {
                        //     $scope.info.reqFlows.push(result.data);
                        //     $scope.info.reqNodeFlows = [];
                        //     $scope.info.reqRelateFlows = [];
                        //     angular.forEach($scope.info.reqFlows, function(flow) {
                        //         if(flow.status == "NODE_UPDATE") {
                        //             $scope.info.reqNodeFlows.push(flow);
                        //         } else {
                        //             $scope.info.reqRelateFlows.push(flow);
                        //         }
                        //     });
                        // }
                        if($scope.info.selectedNodeData.status == "NODE_UPDATE") {
                            var isHasNodeFlow = lodash.findWhere($scope.info.reqNodeFlows, {id: flowItem.id});
                            if(isHasNodeFlow == undefined) {
                                $scope.info.reqNodeFlows.push(flowItem);
                            }
                        } else {
                            var isHasRelateFlow = lodash.findWhere($scope.info.reqRelateFlows, {id: flowItem.id});
                            if(isHasRelateFlow == undefined) {
                                $scope.info.reqRelateFlows.push(flowItem);
                            }
                        }
                        
                        $http.get(matrix_product_url + "/flow/getFlowTreeNode?flowId=" + result.data.id).success(function (result) {
                            if (result.code == "0") {
                                $scope.addNodeToTree(result.data);
                            }
                        });
                    } else {
                        flowItem.level = parseInt(flowData.item.level) + 1;
                        flowItem.status = "ADD";
                        $scope.info.my_tree.set_select_branch_by_id(postParams.bussinessId);
                        $timeout(function() {
                            if(!$scope.info.selectedNodeData.children.length) {
                                $scope.info.selectedNodeData.children = [];
                            }
                            $scope.info.selectedNodeData.children.push(flowItem);
                            $scope.info.reqFlows.push(flowItem);
                            $scope.info.reqNodeFlows = [];
                            $scope.info.reqRelateFlows = [];
                            angular.forEach($scope.info.reqFlows, function(flow) {
                                if(flow.status == "NODE_UPDATE") {
                                    $scope.info.reqNodeFlows.push(flow);
                                } else {
                                    $scope.info.reqRelateFlows.push(flow);
                                }
                            });
                        }, 1000);
                        $http.get(matrix_product_url + "/flow/getFlowTreeNode?flowId=" + result.data.id).success(function (result) {
                            if (result.code == "0") {
                                $scope.addNodeToTree(result.data, true);
                            }
                        });
                    }
                } else {
                    var metaData = {
                        id     : postParams.id,
                        name   : postParams.name,
                        reqId  : postParams.reqId,
                        attrs  : $scope.info.selectedNodeData.metaData.attrs,
                        status : $scope.info.selectedNodeData.metaData.status,
                        bussinessId  : $scope.info.selectedNodeData.metaData.bussinessId,
                        attrConfigId : $scope.info.selectedNodeData.metaData.attrConfigId
                    }
                    $scope.info.selectedNodeData.name = postParams.name;
                    $scope.info.selectedNodeData.metaData = metaData;
                    if($scope.info.hasRelate) {
                        getReqFlows(postParams.reqId);
                    }
                    $scope.info.diagramScope.updateNode();
                }
                $scope.info.currentDiagram = true;
                $rootScope.toasterSuccessInfo(flowData.type == "add" ? "创建成功！" : (flowData.type == "edit" ? "修改成功！" : "复制成功！"));
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    $scope.addNodeToTree = function (data, status) {
        var node = setFlowTree([data], [])[0];
        if(node.type != 1) {
            node.isRelate = "red";
        }
        $scope.info.diagramScope.createNode(node, status);
    }

    //删除流程
    $scope.removeFlow = function (nodeData) {
        if (!nodeData) {
            $rootScope.toasterWarningInfo("请选择要输出的流程！");
            return false;
        }
        //frame为1，不可删除     flow为2，可以删除
        if (nodeData.type == "1") {
            $rootScope.toasterWarningInfo("结构类型流程不能删除！");
            return false;
        }
        var url = matrix_product_url + "/flow/deleteFlow?flowId=" + nodeData.id;
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                var selectedParent = $scope.info.my_tree.get_parent_branch(nodeData);
                var selectedParentArray = [];
                selectedParentArray = selectedParent ? selectedParent.children : $scope.info.flowTree;
                lodash.remove(selectedParentArray, {id: nodeData.id});
                $scope.info.removeFinished = true;
                $scope.info.diagramScope.deleteNode(setFlowTree([nodeData], [])[0]);
                // getReqFlows($scope.info.currentReqId);
                if(nodeData.status == "NODE_UPDATE") {
                    lodash.remove($scope.info.reqNodeFlows, function(flow) {
                        return flow.id == nodeData.id;
                    });
                    $scope.info.reqNodeFlows = angular.copy($scope.info.reqNodeFlows);
                } else {
                    lodash.remove($scope.info.reqRelateFlows, function(flow) {
                        return flow.id == nodeData.id;
                    });
                    $scope.info.reqRelateFlows = angular.copy($scope.info.reqRelateFlows);
                }
                $rootScope.toasterSuccessInfo("删除成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    $scope.getReqFlows = function() {
        getReqFlows($stateParams.reqId);
    }

    //获取req关联的flow列表
    function getReqFlows(reqId) {
        var url = matrix_product_url +"/flow/getReqFlows?reqId="+ reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(!result.data) {
                    $rootScope.toasterErrorInfo("获取req关联流程数据错误！");
                } else {
                    $scope.info.reqNodeFlows = new Array();
                    $scope.info.reqRelateFlows = new Array();
                    angular.forEach(result.data, function(flow) {
                        if(flow.status == "NODE_UPDATE") {
                            $scope.info.reqNodeFlows.push(flow);
                        } else {
                            $scope.info.reqRelateFlows.push(flow);
                        }
                    });
                    $scope.info.reqFlows = result.data;
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //定位
    $scope.goTo = function(relate) {
        $scope.info.jumpToFeature = relate.id;
        if(relate.id) {
            $scope.info.selectedFlow.type = 2;
            $scope.info.my_tree.set_select_branch_by_id(relate.id);
        }
    };

    //关联流程
    $scope.relateFlow = function(nodeData) {
        var flowId = nodeData.id;
        if(!flowId) {
            $rootScope.toasterErrorInfo("关联流程id错误！");
            return false;
        }
        var url = matrix_product_url +"/flow/relateWithFlow?flowId="+ flowId +"&reqId="+ $scope.info.currentReqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(nodeData.status == "NODE_UPDATE") {
                    $scope.info.reqNodeFlows.push(nodeData);
                } else {
                    $scope.info.reqRelateFlows.push(nodeData);
                }
                $scope.info.reqFlows.push(nodeData);
                $rootScope.toasterSuccessInfo("流程关联成功！");
                $scope.info.diagramScope.updateNode(true, "relate");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //解除关联
    $scope.reliveFlow = function(nodeData) {
        var flowId = nodeData.id;
        if(!flowId) {
            $rootScope.toasterErrorInfo("关联流程id错误！");
            return false;
        }
        var url = matrix_product_url +"/flow/dissociateWithFlow?flowId="+ flowId +"&reqId="+ $scope.info.currentReqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(nodeData.status == "NODE_UPDATE") {
                    lodash.remove($scope.info.reqNodeFlows, function(flow) {
                        return flow.id == nodeData.id;
                    });
                    $scope.info.reqNodeFlows = angular.copy($scope.info.reqNodeFlows);
                } else {
                    lodash.remove($scope.info.reqRelateFlows, function(flow) {
                        return flow.id == nodeData.id;
                    });
                    $scope.info.reqRelateFlows = angular.copy($scope.info.reqRelateFlows);
                }
                $rootScope.toasterSuccessInfo("重置成功！");
                $scope.info.diagramScope.updateNode(true);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });

    };

    //标题失焦点保存
    $scope.updateNodeName = function () {
        var nodeDataArray = lodash.findWhere($scope.info.nodeDataArray, {feature_id: $scope.info.model.selectedFlowData.feature_id});
        nodeDataArray.text = $scope.info.model.selectedFlowData.text;
        $scope.info.model = new go.GraphLinksModel($scope.info.nodeDataArray, $scope.info.linkDataArray);
    };

    //切换节点状态保存
    $scope.selectStatusItem = function (item) {
        var nodeDataArray = lodash.findWhere($scope.info.nodeDataArray, {feature_id: $scope.info.model.selectedFlowData.feature_id});
        nodeDataArray.status = item.key;
        nodeDataArray.feature_info.status = item.key;
        nodeDataArray.isHighlighted = true;
        $scope.info.model = new go.GraphLinksModel($scope.info.nodeDataArray, $scope.info.linkDataArray);
    };

    // ************NEW**************

    // 节点内容关联功能点
    $scope.nodeClick = function() {
        $scope.showFlowBuilder = false;
        var url = matrix_product_url +"/feature/featureOccupy?reqId="+ $scope.info.currentReqId +"&id="+ $scope.info.diagramSelected.id;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.diagramSelected.isRelate = "isRelate";
                var nodeDataArray = angular.copy($scope.info.originNodeDataArray);
                var linkDataArray = angular.copy($scope.info.originLinkDataArray);
                angular.forEach(nodeDataArray, function(node) {
                    if(node.id == $scope.info.diagramSelected.id) {
                        node.isRelate = "isRelate";
                    }
                });
                if($scope.info.currentReqId == "-1") {
                    $scope.info.masterFlowDatas = {"nodeDataArray": nodeDataArray || [{ "key":1, "text":"Start", "category":"Start" }], "linkDataArray": linkDataArray || []};
                } else {
                    $scope.info.reqFlowDatas = {"nodeDataArray": nodeDataArray || [{ "key":1, "text":"Start", "category":"Start" }], "linkDataArray": linkDataArray || []};
                }
                $rootScope.toasterSuccessInfo("功能点操作成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $scope.showFlowBuilder = true;
        });
    };

    // 查询
    $scope.searchNode = function () {
        $scope.info.diagramScope.searchNode($scope.info.input);
    }

    //节点回车查询
    $scope.myKeyup = function(e) {
        var keyCode = window.event ? e.keyCode : e.which;
        if(keyCode == 13) {
            $scope.info.diagramScope.searchNode($scope.info.input);
        }
    };

    //切换流程模式（当前，线上，对比）
    $scope.clickStatus = function(status) {
        if(!$scope.info.selectedFlow.id) {
            return false;
        }
        //type    1: frame   2: flow
        if($scope.info.selectedFlow.type == "1") {
            return false;
        }
        var isRelateFlow = "";
        var isRelateFlow = lodash.findWhere($scope.info.reqFlows, {id: $scope.info.selectedFlow.id});
        if(isRelateFlow == undefined) {
            return false;
        }
        switch(status) {
            case "current":
                $scope.info.diagramStatus = "current";
                getFlowDetailsOfNode($scope.info.selectedFlow.id, $stateParams.reqId ? $stateParams.reqId : "-1");
                break;
            case "online":
                $scope.info.diagramStatus = "online";
                getFlowDetailsOfNode($scope.info.selectedFlow.id, "-1");
                break;
            case "compare":
                $scope.info.diagramStatus = "compare";
                getFlowDetailsOfNode($scope.info.selectedFlow.id, $stateParams.reqId ? $stateParams.reqId : "-1");
                getFlowDetailsOfNode($scope.info.selectedFlow.id, "-1");
                break;
        }
    };

    $scope.addFeatureOrFlow = function(data) {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/flowNodeModal.html"),
            controller: "addFeatureOrFlowCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                data: function () {
                    return data;
                }
            }
        });

        modalInstance.result.then(function (nodeItem) {
            if(data.type == "Feature") {
                var feature_info = {
                    reqId: nodeItem.reqId || "-1"
                };
                nodeItem.feature_info = feature_info;
                nodeItem.featureType == "new" ? addNewFeature(nodeItem, data) : getReqFeatureList(nodeItem, data);
            } else {
                nodeItem.featureType == "new" ? addNewFlow(nodeItem, data) : getReqFlowList(nodeItem, data);
            }
        }, function (reason) {
            console.log("关闭modal");
        });
    };

    function addNewFeature(nodeItem, data) {
        delete nodeItem.featureType;
        var url = matrix_product_url + "/feature/createFeature";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(nodeItem),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                nodeItem.id = result.data || "";
                getReqFeatureList(nodeItem, data, "new");
                reqRelateFeature($stateParams.reqId || "-1", result.data);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        })
    }

    function reqRelateFeature(reqId, featureId) {
        var url = matrix_product_url +"/feature/featureOccupy?reqId="+ reqId +"&id="+ featureId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $rootScope.toasterSuccessInfo("创建并关联成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        })
    }

    function addNewFlow(nodeItem, data) {
        delete nodeItem.featureType;
        var url = matrix_product_url + "/flow/createFlow";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(nodeItem),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                nodeItem.id = result.data.id;
                nodeItem.flowname = nodeItem.name;
                reqRelateFlow($stateParams.reqId, result.data.id, nodeItem, data, "new");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        })
    }

    function reqRelateFlow(reqId, flowId, nodeItem, data, flowType) {
        var url = matrix_product_url + "/flow/relateWithFlow?flowId="+ flowId +"&reqId="+ reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $rootScope.toasterSuccessInfo("创建并关联成功！");
                getReqFlowList(nodeItem, data, flowType);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        })
    }

    function setFeatureOrFlow(reqRelateList, nodeItem, data, nodeType) {
        if(nodeType == "new") {
            nodeItem.isRelate = "isRelate";
        } else {
            nodeItem = isRealte(reqRelateList, nodeItem);
        }
        if(data.type == "Feature" && !nodeItem.featureKind) {
            nodeItem.featureKind = data.featureKind;
        }
        nodeItem.isOldItem = "newItem";
        data.type == "Feature" ? nodeItem.feature_id = nodeItem.id : nodeItem.flow_id = nodeItem.id;
        if(data.status == "update") {
            var e = $scope.info.diagramScope.e;
            var partData = $scope.info.diagramScope.partData;
            var category = $scope.info.diagramScope.category;
            nodeItem.isNew = category == "Feature" ? "修改节点" : "修改流程";
            var data = {};
            $scope.info.diagramScope.changeNodeCategory(e, partData, category, data, nodeItem);
        } else {
            var obj = $scope.info.diagramScope.obj;
            var category = $scope.info.diagramScope.category;
            nodeItem.isNew = category == "Feature" ? "新增节点" : "新增流程";
            $scope.info.diagramScope.propAddNodeAndLink(obj, category, nodeItem);
        }
    }

    // 获取关联流程（非节点变更）
    function getReqFlowList(nodeItem, data, flowType) {
        var url = matrix_product_url +"/flow/getReqFlows?reqId="+ $stateParams.reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.reqNodeFlows = [];
                $scope.info.reqRelateFlows = [];
                angular.forEach(result.data, function(flow) {
                    if(flow.status != "NODE_UPDATE") {
                        $scope.info.reqFlowList.push(flow);
                    }
                    if(flow.status == "NODE_UPDATE") {
                        $scope.info.reqNodeFlows.push(flow);
                    } else {
                        $scope.info.reqRelateFlows.push(flow);
                    }
                });
                setFeatureOrFlow($scope.info.reqFlowList, nodeItem, data, flowType);
            } else {
                $rootScope.toasterErrorInfo("获取关联流程数据错误！");
            }
        });
    }

    // 获取关联功能点
    function getReqFeatureList(nodeItem, data, nodeType) {
        var url = matrix_product_url +"/feature/getAllFeatureForReq?reqId="+ $stateParams.reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.reqFeatureList = result.data || [];
                setFeatureOrFlow($scope.info.reqFeatureList, nodeItem, data, nodeType);
            } else {
                $rootScope.toasterErrorInfo("获取关联功能点数据错误！");
            }
        });
    }

    function isRealte(data, nodeItem) {
        nodeItem.isRelate = "";
        var isRelate = lodash.findIndex(data, function(d) {
            return d.id == nodeItem.id;
        });
        if(isRelate != -1) {
            nodeItem.isRelate = "isRelate";
        } else {
            nodeItem.isRelate = "isAddNode";
        }
        return nodeItem;
    }

    // 获取点击的节点详细信息
    $scope.getNodeDetails = function(data) {
        console.log("获取点击节点信息");
        console.log(data);
        $scope.info.diagramSelected = data;
        $scope.$apply();
    };

    function updateFlowDetails2() {
        $scope.info.diagramScope.save();
        console.log("外部调用获取里面的值");
        var nodeData = JSON.parse($scope.info.diagramScope.flowData);
        console.log(nodeData.nodeDataArray);
        console.log(nodeData.linkDataArray);
        var currentDate = Number(new Date());
        var postParams = {
            reqId: $stateParams.reqId ? $stateParams.reqId : "-1",
            flowId: $scope.info.flowId, 
            attrs: {
                "date": currentDate,
                "version": $scope.info.flowDetails.attrs.version,
                "req_snapshot": $scope.info.flowDetails.attrs.req_snapshot,
                "master_version": $scope.info.flowDetails.attrs.master_version,
                "nodeDataArray": nodeData.nodeDataArray || [],
                "linkDataArray": nodeData.linkDataArray || [],
            }
        };

        console.log(JSON.stringify(preventCircularJson(postParams)));
        var url = matrix_product_url + "/flow/updateReqFlowContent";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                $rootScope.toasterSuccessInfo("保存成功！");
            } else {
                $rootScope.toasterErrorInfo("保存失败，请刷新重试！");
            }
        });
    };
}]);

app.controller("addFeatureOrFlowCtrl", ["$scope", "$stateParams", "$rootScope", "$modalInstance", "$http", "data", "lodash", function($scope, $stateParams, $rootScope, $modalInstance, $http, data, lodash) {
    var flagName = "";
    switch(data.flag) {
        case "JUMP": 
            flagName = "【展示页面】";
            break;
        case "UI": 
            flagName = "【页面交互】";
            break;
        case "FORM": 
            flagName = "【信息提交】";
            break;
        case "SCAN": 
            flagName = "【扫描】";
            break;
    }
    $scope.flowTypeName = "引入" + (data.type == "Feature" ? ("功能点" + (flagName)) : "流程");
    $scope.promptName = data.type == "Feature" ? "请选择功能点" : "请选择流程";
    $scope.type = data.type;
    $scope.isAddFeatureOrFlow = true;
    $scope.sysArray = config_flow_legend_sys;
    $scope.ffDataArray = [];
    $scope.currentRadio = "select";
    $scope.addFeatureOrFlowName = "";
    $scope.treeData = [];
    $scope.isMaster = "-1";
    $scope.sltBranch = [];
    $scope.sltSysItem = lodash.first(config_flow_legend_sys);
    $scope.featureKindArray = config_feature_details_type;
    $scope.sltKindItem = lodash.findWhere(config_feature_details_type, {key: data.flag});

    data.type == "Feature" ? getAllFeature($scope.sltSysItem.key, $scope.sltKindItem.key) : getFlowTree();

    $scope.switchRadio = function(type) {
        $scope.sltKindItem = lodash.findWhere(config_feature_details_type, {key: data.flag});
        $scope.currentRadio = type;
        if(type == "new") {
            data.type == "Feature" ? getFeatureTree($scope.sltSysItem.key) : getFlowFrameTree();
        }
    }

    $scope.switchKind = function(item) {
        $scope.sltKindItem = item;
        $scope.sltLegendItem = "";
        getAllFeature($scope.sltSysItem.key || lodash.first(config_flow_legend_sys).key, item.key);
    }

    $scope.switchMasterOrReq = function(type) {
        $scope.isMaster = type == "master" ? "-1" : $stateParams.reqId;
    }

    $scope.switchSys = function(item) {
        $scope.sltSysItem = item;
        $scope.sltLegendItem = "";
        $scope.currentRadio == "new" ? getFeatureTree(item.crtname) : getAllFeature(item.crtname, $scope.sltKindItem.key);
    }

    if(data.type != "Feature") {
        getFlowFrameTree();
    }

    function getFeatureTree(sys) {
        $("#showNewLoading").css("display", "block");
        $("#newFeatureTree").css("display", "none");
        var url = matrix_product_url + "/feature/getFeatureBaseTree?featureSys="+ sys;
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.treeData = result.data[0].children;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $("#showNewLoading").css("display", "none");
            $("#newFeatureTree").css("display", "block");
        });
    };

    //获取流程架构树数据
    function getFlowFrameTree() {
        $("#showNewLoading").css("display", "block");
        $("#newFeatureTree").css("display", "none");
        var url = matrix_product_url + "/flowFrame/getFlowFrameTree";
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.treeData = result.data.children;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $("#showNewLoading").css("display", "none");
            $("#newFeatureTree").css("display", "block");
        });
    };

    $scope.selectProductLine = function (item, selectedItems) {
        $scope.sltBranch = item;
    };

    // 获取功能点数据
    function getAllFeature(sys, featureKind) {
        $("#showLoading").css("display", "block");
        $("#showList").css("display", "none");
        $scope.ffDataArray = new Array();
        var url = matrix_product_url +"/feature/getFeature?withPrototype=1&withAttr=0";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                angular.forEach(result.data, function(data) {
                    data.crtname = (data.path || "") + "/" + (data.featureName || "");
                });
                angular.forEach(result.data, function(resData) {
                    if(sys) {
                        if(resData.sys == sys) {
                            if(featureKind == resData.featureKind) {
                                $scope.ffDataArray.push(resData);
                            }
                        }
                    } else {
                        $scope.ffDataArray.push(resData);
                    }
                });
            } else {
                $rootScope.toasterErrorInfo("获取功能点数据错误！");
            }
            $("#showLoading").css("display", "none");
            $("#showList").css("display", "block");
        });
    }

    // 获取流程树
    function getFlowTree() {
        $("#showLoading").css("display", "block");
        $("#showList").css("display", "none");
        var url = matrix_product_url + "/flow/getFlowTree";
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.ffDataArray = setFlowLegendPath(result.data.children, [], "");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $("#showLoading").css("display", "none");
            $("#showList").css("display", "block");
        });
    };

    // 解析流程树数据
    function setFlowLegendPath(featureTree, resultFeatureArray, featureName) {
        angular.forEach(featureTree, function (feature, index) {
            var pathUrl = featureName ? featureName + "/" + feature.name : feature.name;
            //type  1: frame   2: flow
            if(feature.type == "2") {
                var featureItem = {
                    crtname: pathUrl,
                    flowname: feature.name,
                    status: feature.status,
                    id: feature.id,
                    path: featureName
                }
                resultFeatureArray.push(featureItem);
            }
            if (feature.children && feature.children.length) {
                setFlowLegendPath(feature.children, resultFeatureArray, feature.name);
            }
        });
        return resultFeatureArray;
    };

    $scope.createClick = function () {
        if($scope.currentRadio == "select") {
            if (!$scope.sltLegendItem) {
                $rootScope.toasterWarningInfo("引入节点数据不能为空！");
                return false;
            }
        }
        if($scope.currentRadio == "new") {
            if(data.type == "Feature") {
                if(!$scope.sltSysItem.crtname) {
                    $rootScope.toasterWarningInfo("请选择系统类型！");
                    return false;
                }
                if($scope.sltBranch.nodeType != "page") {
                    $rootScope.toasterWarningInfo("父节点类型错误，请重新选择！");
                    return false;
                }
                if(lodash.trim($scope.addFeatureOrFlowName) == "") {
                    $rootScope.toasterWarningInfo("新建名称不能为空！");
                    return false;
                }
                var featureInfo = {
                    featureType: "new",
                    attr: {
                        "feature_name": lodash.trim($scope.addFeatureOrFlowName)
                    },
                    featureName: lodash.trim($scope.addFeatureOrFlowName),
                    featureKind: $scope.sltKindItem.key,
                    originalPageId: $scope.sltBranch.id,
                    pageId: $scope.sltBranch.id,
                    path: ($scope.sltBranch.metaData.menuPath || "") + "/" + ($scope.sltBranch.name || ""),
                    reqId: $scope.isMaster,
                    sys: $scope.sltSysItem.crtname
                };
            } else {
                if($scope.sltBranch.type != "FLOW_FRAME") {
                    $rootScope.toasterWarningInfo("父节点类型错误，请重新选择！");
                    return false;
                }
                if(lodash.trim($scope.addFeatureOrFlowName) == "") {
                    $rootScope.toasterWarningInfo("新建名称不能为空！");
                    return false;
                }
                var flowInfo = {
                    featureType: "new",
                    attrs: {},
                    bussinessId: $scope.sltBranch.id,
                    name: lodash.trim($scope.addFeatureOrFlowName),
                    reqId: $scope.isMaster,
                    status: "ADD",
                    flowName: lodash.trim($scope.addFeatureOrFlowName),
                    path: $scope.sltBranch.name
                };
            }
        }

        $modalInstance.close($scope.currentRadio == "select" ? $scope.sltLegendItem : (data.type == "Feature" ? featureInfo : flowInfo));
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);

app.controller("editFlowCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "type", "defaultValue", "flowDetails", function ($scope, $rootScope, $modalInstance, $http, type, defaultValue, flowDetails) {
    $scope.flowId = "";
    $scope.flowType = type;
    $scope.flowTypeName = type == "add" ? (defaultValue == "frame" ? "新建架构" : "新建流程") : (type == "edit" ? "编辑流程" : "复制流程");
    $scope.treeData = [];
    $scope.flowItem = {};
    $scope.dataCrtValue = "请选择节点";
    if(type == "edit") {
        if(defaultValue) {
            $scope.flowName = defaultValue.name;
        } else {
            $scope.flowName = "";
        }
    } else {
        $scope.flowName = "";
    }
    if(type == "copy") {
        $scope.flowName = defaultValue.name + " copy";
        getNodeByFlowFrameId(defaultValue.parentId);
        getFlowFrameTree();
    }

    // 根据flowframeId获取节点信息
    function getNodeByFlowFrameId(copyFlowParentId) {
        if(!copyFlowParentId) {
            $rootScope.toasterWarningInfo("流程架构id未定义！");
            return false;
        }
        var url = matrix_product_url + "/flowFrame/getTreeNode?flowFrameId=" + copyFlowParentId;
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.dataCrtValue = result.data.name || "请选择节点";
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    }

    //获取流程架构树数据
    function getFlowFrameTree() {
        var url = matrix_product_url + "/flowFrame/getFlowFrameTree";
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.treeData = result.data.children;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    $scope.selectProductLine = function (item, selectedItems) {
        $scope.flowId = item.id;
        $scope.flowItem = item;
        $scope.dataCrtValue = item.name;
    };

    $scope.createClick = function () {
        if ($scope.flowName == defaultValue.name) {
            $rootScope.toasterWarningInfo("流程名称不能重复！");
            return false;
        }
        if(type == "copy") {
            if (!$scope.flowId) {
                $rootScope.toasterWarningInfo("复制节点不能为空！");
                return false;
            }
        }
        var flowData = {
            id: $scope.flowId,
            name: $scope.flowName,
            type: type,
            attrs: flowDetails.attrs,
            item: $scope.flowItem
        };
        $modalInstance.close(flowData);
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);
